import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  Button, 
  Carousel, 
  Rate, 
  Modal, 
  InputNumber,
  Radio,
  Badge,
  Divider,
  Tag,
  Image
} from 'antd';
import { 
  ArrowLeftOutlined, 
  MoreOutlined, 
  HeartOutlined, 
  HeartFilled,
  ShoppingCartOutlined,
  CustomerServiceOutlined,
  ShareAltOutlined,
  StarFilled,
  TruckOutlined,
  SafetyOutlined,
  GiftOutlined
} from '@ant-design/icons';
import { productAPI } from '../../services/api';
import { addToCart, addToFavorites, removeFromFavorites, isFavorite, getCart } from '../../utils/storage';
import { isUserAuthenticated, getUserInfo } from '../../utils/auth';
import { message } from '../../utils/message';
import './ProductDetail.css';

const ProductDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [product, setProduct] = useState(null);
  const [loading, setLoading] = useState(true);
  const [selectedSpecs, setSelectedSpecs] = useState({});
  const [quantity, setQuantity] = useState(1);
  const [showSpecModal, setShowSpecModal] = useState(false);
  const [actionType, setActionType] = useState(''); // 'cart' or 'buy'
  const [isFav, setIsFav] = useState(false);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const carouselRef = React.useRef(null);
  
  const userInfo = getUserInfo();
  const cart = getCart();
  const cartCount = cart.length; // 显示商品种类数，不是总数量

  useEffect(() => {
    fetchProductDetail();
  }, [id]);

  useEffect(() => {
    if (product) {
      setIsFav(isFavorite(product.id));
    }
  }, [product]);

  const fetchProductDetail = async () => {
    try {
      const response = await productAPI.getProductById(id);
      if (response.success) {
        setProduct(response.data);
        // 初始化默认规格
        const defaultSpecs = {};
        response.data.specs?.forEach(spec => {
          if (spec.options.length > 0) {
            defaultSpecs[spec.name] = spec.options[0].name;
          }
        });
        setSelectedSpecs(defaultSpecs);
      }
    } catch (error) {
      message.error('获取商品详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSpecChange = (specName, value) => {
    setSelectedSpecs({
      ...selectedSpecs,
      [specName]: value
    });
  };

  const getCurrentPrice = () => {
    if (!product?.specs) return product?.price || 0;
    
    // 根据选中的规格计算价格
    for (const spec of product.specs) {
      const selectedOption = spec.options.find(
        option => option.name === selectedSpecs[spec.name]
      );
      if (selectedOption) {
        return selectedOption.price;
      }
    }
    return product.price;
  };

  const handleAddToCart = () => {
    if (!isUserAuthenticated()) {
      navigate('/app/login', { state: { from: { pathname: `/app/product/${id}` } } });
      return;
    }
    
    setActionType('cart');
    setShowSpecModal(true);
  };

  const handleBuyNow = () => {
    if (!isUserAuthenticated()) {
      navigate('/app/login', { state: { from: { pathname: `/app/product/${id}` } } });
      return;
    }
    
    setActionType('buy');
    setShowSpecModal(true);
  };

  const handleConfirmAction = () => {
    // 添加库存验证
    if (quantity > product.stock) {
      message.error(`商品库存不足，当前库存为${product.stock}件`);
      setQuantity(product.stock);
      return;
    }

    const cartItem = {
      ...product,
      selectedSpecs,
      quantity,
      price: getCurrentPrice(),
      cartId: Date.now() + Math.random()
    };

    if (actionType === 'cart') {
      // 检查购物车中是否已有相同商品，并验证总数量是否超过库存
      const cart = getCart();
      const existingItem = cart.find(item => 
        item.id === product.id && 
        JSON.stringify(item.selectedSpecs) === JSON.stringify(selectedSpecs)
      );
      
      const totalQuantity = existingItem ? existingItem.quantity + quantity : quantity;
      
      if (totalQuantity > product.stock) {
        message.error(`添加数量过多，超出库存。当前库存剩余${product.stock - (existingItem?.quantity || 0)}件`);
        return;
      }
      
      addToCart(cartItem);
      message.success('已加入购物车');
      setShowSpecModal(false);
    } else if (actionType === 'buy') {
      // 立即购买，跳转到订单确认页
      navigate('/app/order/confirm', { 
        state: { 
          products: [cartItem],
          fromBuyNow: true
        } 
      });
    }
  };

  const handleToggleFavorite = () => {
    if (!isUserAuthenticated()) {
      navigate('/app/login', { state: { from: { pathname: `/app/product/${id}` } } });
      return;
    }

    if (isFav) {
      removeFromFavorites(product.id);
      setIsFav(false);
      message.success('已取消收藏');
    } else {
      addToFavorites(product);
      setIsFav(true);
      message.success('已加入收藏');
    }
  };

  const handleShare = () => {
    message.info('分享功能开发中');
  };

  const handleMore = () => {
    message.info('更多功能开发中');
  };

  const handleCustomerService = () => {
    message.info('客服功能开发中');
  };

  const handleThumbnailClick = (index) => {
    setCurrentImageIndex(index);
    if (carouselRef.current) {
      carouselRef.current.goTo(index);
    }
  };

  if (loading) {
    return (
      <div className="product-detail-loading">
        <div className="loading-spinner"></div>
      </div>
    );
  }

  if (!product) {
    return (
      <div className="product-detail-error">
        <div>商品不存在</div>
        <Button onClick={() => navigate(-1)}>返回</Button>
      </div>
    );
  }

  return (
    <div className="product-detail-container">
      {/* 头部导航 */}
      <div className="product-detail-header">
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
          className="header-back-btn"
        />
        <div className="header-actions">
          <Button 
            type="text" 
            icon={<ShareAltOutlined />}
            onClick={handleShare}
            className="header-action-btn"
          />
          <Badge count={cartCount} size="small">
            <Button 
              type="text" 
              icon={<ShoppingCartOutlined />}
              onClick={() => navigate('/app/cart')}
              className="header-action-btn"
            />
          </Badge>
          <Button 
            type="text" 
            icon={<MoreOutlined />}
            onClick={handleMore}
            className="header-action-btn"
          />
        </div>
      </div>

      {/* 商品图片轮播 */}
      <div className="product-images-section">
        <Carousel 
          autoplay={false} 
          dots={false}
          afterChange={setCurrentImageIndex}
          ref={carouselRef}
        >
          {product.images.map((image, index) => (
            <div key={index} className="product-image-slide">
              <Image
                src={image}
                alt={product.name}
                className="product-detail-image"
                preview={{
                  src: image,
                  mask: <div className="image-preview-mask">点击查看大图</div>
                }}
              />
            </div>
          ))}
        </Carousel>
        <div className="image-indicator">
          {currentImageIndex + 1}/{product.images.length}
        </div>
        <div className="image-thumbnails">
          {product.images.map((image, index) => (
            <div
              key={index}
              className={`thumbnail-item ${index === currentImageIndex ? 'active' : ''}`}
              onClick={() => handleThumbnailClick(index)}
            >
              <img src={image} alt={`${product.name} ${index + 1}`} />
            </div>
          ))}
        </div>
      </div>

      {/* 商品基本信息 */}
      <div className="product-info-section">
        {/* 价格区域 */}
        <div className="price-section">
          <div className="price-row">
            <span className="current-price">¥{getCurrentPrice()}</span>
            {product.originalPrice && product.originalPrice > getCurrentPrice() && (
              <span className="original-price">¥{product.originalPrice}</span>
            )}
            <div className="price-tags">
              {product.originalPrice && product.originalPrice > getCurrentPrice() && (
                <Tag color="red" className="discount-tag">
                  立减{(product.originalPrice - getCurrentPrice()).toFixed(0)}元
                </Tag>
              )}
            </div>
          </div>
          {/* <div className="coupon-row">
            <Tag color="red" className="coupon-tag">券</Tag>
            <span className="coupon-text">满8减1</span>
          </div> */}
        </div>

        {/* 商品标题和信息 */}
        <div className="title-section">
          <h1 className="product-title">{product.name}</h1>
          <div className="product-subtitle">
            {product.subtitle}
          </div>
        </div>

        {/* 销量和评价 */}
        <div className="stats-section">
          <div className="stats-row">
            <span className="sales-text">24小时内63人已买</span>
            <div className="rating-section">
              <StarFilled style={{ color: '#ffa940', fontSize: '12px' }} />
              <span className="rating-text">多人评价"好"</span>
            </div>
          </div>
        </div>
      </div>

      {/* 物流信息 */}
      <div className="delivery-section">
        <div className="delivery-item">
          <TruckOutlined className="delivery-icon" />
          <div className="delivery-info">
            <div className="delivery-main">预计明天发货 | 承诺3天内发货</div>
            <div className="delivery-detail">浙江金华 快递: 免运费</div>
          </div>
        </div>
      </div>

      {/* 保障信息 */}
      <div className="guarantee-section">
        <div className="guarantee-item">
          <SafetyOutlined className="guarantee-icon" />
          <span>7天无理由退货</span>
        </div>
        <div className="guarantee-item">
          <GiftOutlined className="guarantee-icon" />
          <span>极速退款</span>
        </div>
        <div className="guarantee-item">
          <span className="stock-status">出售状态: 现货</span>
        </div>
      </div>

      {/* 规格选择 */}
      {product.specs && product.specs.length > 0 && (
        <div className="specs-section">
          {product.specs.map(spec => (
            <div key={spec.name} className="spec-group">
              <div className="spec-title">{spec.name}</div>
              <div className="spec-options">
                {spec.options.map(option => (
                  <div
                    key={option.name}
                    className={`spec-option ${selectedSpecs[spec.name] === option.name ? 'active' : ''}`}
                    onClick={() => handleSpecChange(spec.name, option.name)}
                  >
                    {option.name}
                    {option.price !== product.price && (
                      <span className="spec-price-diff"> ¥{option.price}</span>
                    )}
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 商品详情 */}
      <div className="product-description-section">
        <div className="description-title">商品详情</div>
        <div className="description-content">{product.description}</div>
      </div>

      {/* 底部操作栏 */}
      <div className="product-bottom-actions">
        <div className="bottom-action-left">
          <div className="action-item" onClick={() => navigate('/app')}>
            <div className="action-icon">🏠</div>
            <span className="action-text">其他</span>
          </div>
          <div className="action-item" onClick={handleCustomerService}>
            <div className="action-icon">💬</div>
            <span className="action-text">客服</span>
          </div>
          <div className="action-item" onClick={handleToggleFavorite}>
            <div className="action-icon">
              {isFav ? '❤️' : '🤍'}
            </div>
            <span className="action-text">收藏</span>
          </div>
        </div>
        
        <div className="bottom-action-right">
          <Button 
            className="add-cart-btn"
            onClick={handleAddToCart}
          >
            加入购物车
          </Button>
          <Button 
            type="primary"
            className="buy-now-btn"
            onClick={handleBuyNow}
          >
            领券购买
          </Button>
        </div>
      </div>

      {/* 规格选择弹窗 */}
      <Modal
        title="选择商品规格"
        open={showSpecModal}
        onCancel={() => setShowSpecModal(false)}
        footer={null}
        className="product-spec-modal"
        width={300}
      >
        <div className="spec-modal-content">
          <div className="modal-product-info">
            <img src={product.images[0]} alt={product.name} className="modal-product-image" />
            <div className="modal-product-details">
              <div className="modal-price">¥{getCurrentPrice()}</div>
              <div className="modal-stock">库存 {product.stock} 件</div>
              <div className="modal-selected-specs">
                已选择：{Object.entries(selectedSpecs).map(([key, value]) => (
                  <span key={key}>{value} </span>
                ))}
              </div>
            </div>
          </div>

          {product.specs && product.specs.map(spec => (
            <div key={spec.name} className="modal-spec-group">
              <div className="spec-group-title">{spec.name}</div>
              <div className="spec-options-grid">
                {spec.options.map(option => (
                  <div
                    key={option.name}
                    className={`spec-option-item ${selectedSpecs[spec.name] === option.name ? 'selected' : ''}`}
                    onClick={() => handleSpecChange(spec.name, option.name)}
                  >
                    {option.name}
                  </div>
                ))}
              </div>
            </div>
          ))}

          <div className="quantity-selector">
            <span className="quantity-label">数量</span>
            <div className="quantity-controls">
              <Button 
                size="small"
                onClick={() => setQuantity(Math.max(1, quantity - 1))}
                disabled={quantity <= 1}
              >
                -
              </Button>
              <InputNumber
                min={1}
                max={product.stock}
                value={quantity}
                onChange={(value) => {
                  if (value > product.stock) {
                    message.warning(`库存不足，当前库存为${product.stock}件`);
                    setQuantity(product.stock);
                  } else {
                    setQuantity(value);
                  }
                }}
                className="quantity-input"
                controls={false}
              />
              <Button 
                size="small"
                onClick={() => {
                  if (quantity < product.stock) {
                    setQuantity(quantity + 1);
                  } else {
                    message.warning(`已达到最大库存数量：${product.stock}件`);
                  }
                }}
                disabled={quantity >= product.stock}
              >
                +
              </Button>
            </div>
          </div>

          <Button
            type="primary"
            block
            size="large"
            onClick={handleConfirmAction}
            className="modal-confirm-btn"
          >
            {actionType === 'cart' ? '加入购物车' : '立即购买'}
          </Button>
        </div>
      </Modal>
    </div>
  );
};

export default ProductDetail; 